<template>
	<view>
		<view class="mar-10 bg-white pad-10">
			<view class="text-center">
				<view class="line-height-35">支付金额（元）</view>
				<view class="line-height-35 color-red">{{form.payMoney}}</view>
			</view>
			<view class="dashed"></view>
			<view class="between line-height-35">
				<view>业务类型</view>
				<view>自助开单缴费</view>
			</view>
		</view>
		<view class="mar-10"> 选择支付方式 </view>
		<view class="mar-10 bg-white">
			<view class="between center line-height-35 wxzf">
				<view class="flex-start center pad-0-20">
					<image class="img" src="/static/images/patient/wxzf.png"></image>
					<view class="mar-10">微信支付</view>
				</view>
				<view>
					<u-checkbox-group>
						<u-checkbox v-model="checkedwx" shape="circle" @change="changeWxzf"></u-checkbox>
					</u-checkbox-group>
				</view>
			</view>
			<view class="between center  line-height-35 ybzf">
				<view class="flex-start center pad-0-20">
					<image class="img" src="/static/images/patient/ybzf.png"></image>
					<view class="mar-10">医保支付</view>
				</view>
				<view>
					<u-checkbox-group>
						<u-checkbox v-model="checkedyb" shape="circle" @change="changeYbzf"></u-checkbox>
					</u-checkbox-group>
				</view>
			</view>
		</view>
		<view class="notice-text pad-10 mar-10">
			<view class="text-center line-height-35">温馨提示</view>
			<view>
				<view>1、如需门诊医疗收费收据〔发票),请前往收费处打印。</view>
				<view>2、交易扣费成功，系统交费失败时，您可以重新发起支付或选择其他途径继续交费。支付失败款项将在5个工作日内，原路返还到您的账号中，请您放心使用。</view>
			</view>
		</view>
		<ButtonVue v-if="hadOrderNo" content="确认" @click="confirm"></ButtonVue>
		<u-mask :show="showMask" @click="showMask = false">
			<view class="mask">
				<view class="mask-content">正在拉起支付...</view>
			</view>
		</u-mask>
	</view>
</template>

<script>
	import {
		selfBillingUpdate
	} from '../../api/selfBilling';
	import {
		payPatientRegisterBudget,
		payPatientRegisterSettlement,
		patientFeeBudget,
		patientFeeSettlement
	} from '../../api/pay';
	import {
		reserveRegister
	} from '../../api/reserve';
	import {
		listPayType
	} from '../../utils/listPayType';
	import {
		listPayStatus
	} from '../../utils/listPayStatus';
	import {
		listPaySourceType
	} from '../../utils/listPaySourceType';
	import {
		dateDefault,
		dateFormat,
		getDateBySecond,
		getFutureSeconds,
		getSecondBetweenDates
	} from '../../utils/assist';
	import {
		mapGetters,
		mapActions
	} from 'vuex'
	import {
		doctorGuidanceTemplateSelect
	} from '../../api/doctorGuidanceTemplate';
	import {
		patientGuidanceAddBatch,
		patientGuidanceSelect
	} from '../../api/patientGuidance';
	import {
		weChatRegisterPay,
		weChatRegisterBack
	} from '../../api/weChat';
	import ButtonVue from '../../components/Button/Button.vue';
	import {
		payOrderUpdate,
		selectPayOrder
	} from '../../api/payOrder';
	import {
		dictionarySelect
	} from '../../api/dictionary';
	export default {
		components: {
			ButtonVue,
		},
		data() {
			return {
				countTime: '',
				checkedwx: true,
				checkedyb: false,
				payType: 1,
				payTypeName: '',
				payStatus: 1,
				form: {},
				receiptNo: '', //预约收据号
				payOrderNo: "", //订单编号
				payOrder: {}, //支付订单
				payResult: "",
				hadOrderNo: true, //表示有订单，有订单才显示订单支付按钮
				showMask: false,
				data: '' //得到当前传递过来的自助开单数据
			}
		},
		onLoad(e) {
			this.data = JSON.parse(e.item)
			this.init();
		},
		computed: {
			...mapGetters(['userId', "userInfo"])
		},
		methods: {
			init() {
				console.log(this.form)
				if (!this.userInfo.patId) {
					this.$u.toast('请重新选择就诊卡')
					return;
				}

				let listPay = listPayType.filter(res =>
					res.type == this.payType
				)
				let listStatus = listPayStatus.filter(res => res.status = this.payStatus)
				if (this.checkedwx) {
					this.payType = 1;
					this.payTypeName = listPay[0].name
					// 1:根据病人医保代码结算
					// 2:自费结算
					this.settleType = 2
				} else {
					this.settleType = 1;
				}
				let orderTime = getDateBySecond(-900);
				// 查询当前订单
				selectPayOrder({
					patId: this.userInfo.patId,
					orderTime: orderTime,
					paySourceType: this.data.paySourceType,
					regId: this.data.preId,
					payStatus: 1,
					page: 1,
					size: 5,
					orderBy: "create_time desc"
				}).then(res => {
					console.log(res)
					if (res.length > 0) {
						res = res[0]
						this.form = res;
						let ct = new Date(res.orderTime);
						let seconds = getFutureSeconds(new Date(res.orderTime))
						let num = 15 * 60 + seconds
						console.log(num)
						if (num > 0) {
							// 倒计时等于现在的日期，和挂号的日期比较得到秒
							this.timestamp = num;
						}
					} else {
						// 表示为创建订单
						this.$u.toast('还为创建订单，不能支付')
						this.hadOrderNo = false
					}

				})
			},

			changeWxzf(e) {
				if (e.value) {
					this.checkedyb = false;
				}
			},
			changeYbzf(e) {
				if (e.value) {
					this.checkedwx = false;
				}
			},
			confirm() {
				this.showMask = true;
				if (this.checkedwx) {
					this.payType = 1;
					this.payTypeName = listPayType.filter(res => {
						res.type == this.payType
					}).name
				}
				this.form.settleType = this.settleType
				this.form.payTime = dateFormat("yyyy-MM-dd HH:mm:ss", new Date())
				this.form.payOrderNo = dateFormat("yyyyMMddHHmmss", new Date()) + "_" + this.userInfo.patId
				this.form.deptCode = this.form.departmentCode
				this.form.deptName = this.form.departmentName
				this.form.operatorDeptCode = this.form.departmentCode
				this.form.patId = this.userInfo.patId
				this.form.prePriceSet = this.form.regId
				this.form.deductAccountType = 1
				this.form.feeTime = this.form.payTime
				this.form.payMoney = this.form.money

				// 判断是否需要预算
				dictionarySelect({
					code: 'SetBoolRegisterIsNeedBudget',
					status: 1
				}).then(res => {
					console.log(res)
					if (res.length > 0) {
						if (res[0].describe == '1') {
							this.budget()
						} else {
							this.onBridgeReady()
						}
					} else {
						this.onBridgeReady()
					}
				})

			},
			budget() {
				let feeObj = {
					patId: this.form.patId,
					prePriceSet: this.form.regId,
					regId: 0,
					deductAccountType: this.form.deductAccountType,
					settleType: 2,
					medCode: "01"
				}
				// 点击支付时去预算，如果预算成功，才拉取微信支付窗口
				patientFeeBudget(feeObj).then(res => {
					console.log(res)
					if (res.length > 0) {
						this.form.receiptNo = res[0].receiptNo //收据号
						// this.form.regId = res[0].regId
						this.form.totalAmount = res[0].totalAmount //总金额
						this.form.amountPayable = res[0].amountPayable //应付金额
						// this.form.accountBalance = res[0].accountBalance //账户余额
						this.form.selfPayMoney = res[0].selfPayMoney //自费金额
						this.form.accountNo = '111'
						this.form.paySerialNo = "wx_" + res[0].regId //支付流水号
						this.form.orderId = this.form.payOrderNo
						this.form.payType = 9 //支付类型 微信支付
						this.form.payTypeName = "微信支付" //支付类型 微信支付
						this.onBridgeReady()
					}
				})
			},
			onBridgeReady() {
				console.log(this.form)
				// return
				let that = this;
				if (navigator.userAgent.match(/MicroMessenger/i)) {
					// 拿到挂号信息后去后端拿支付参数数据
					weChatRegisterPay({
						body: this.form.payOrderNo,
						orderId: this.form.payOrderNo,
						payMoney: this.form.payMoney,
						// payMoney: '0.01',
						spbCreIp: '127.0.0.1',
						openId: this.userInfo.openId,
						account: this.userInfo.openId
					}).then(res => {
						console.log(res)
						if (res.status == 'F') {
							that.$u.toast(res.msg)
							return
						}
						this.showMask = false
						// 支付
						WeixinJSBridge.invoke('getBrandWCPayRequest', {
								"appId": res.result.appId, //公众号ID，由商户传入     
								"timeStamp": res.result.timeStamp, //时间戳，自1970年以来的秒数     
								"nonceStr": res.result.nonceStr, //随机串     
								"package": res.result.package,
								// "signType": "RSA",     //微信签名方式：     
								"signType": "MD5", //微信签名方式：
								"paySign": res.result.paySign //微信签名 
							},
							function(res) {
								if (res.err_msg == "get_brand_wcpay_request:ok") {
									that.paySuccessWechatBack()
								}
							});
					})
				} else {
					this.$u.toast('请在微信中打开此页面')
					console.log("请在微信中打开此页面");
				}
			},
			// 支付成功 挂号回调
			paySuccessWechatBack() {
				// 回调,查询是否支付成功
				weChatRegisterBack({
					orderId: this.form.payOrderNo
				}).then(resBack => {
					if (resBack.result.tradeState != 'SUCCESS') {
						this.$u.toast(res.result.tradeStateDesc)
						return;
					}
					//微信支付后返回的流水号
					// 调用结算,结算成功,才算成功
					this.registerSettlement()
				}).finally(e => {
					this.payResult.ff = JSON.stringify(e)
				})

			},
			registerSettlement() {
				this.form.payChannel = this.checkedwx ? 2 : 4
				// 需要挂号结算和修改订单信息
				this.form.payStatus = 3
				this.form.payStatusName = '支付成功'
				patientFeeSettlement(this.form).then(res => {
					this.methodUpdatePayOrder()
				})
			},
			methodUpdatePayOrder() {
				// 修改订单
				payOrderUpdate(this.form).then(res => {
					if (this.form.paySourceType == 5) {
						this.methodUpdateSelfBilling()
					} else {
						this.toPaySuccess()
					}
				})
			},
			methodUpdateSelfBilling() {
				// 修改自助开单状态
				this.data.payStatus = 1
				this.data.payStatusName = '已支付'
				this.data.orderId = this.form.payOrderNo
				selfBillingUpdate(this.data).then(res => {
					this.toPaySuccess()
				})
			},
			toPaySuccess() {
				uni.reLaunch({
					url: `/pages/Pay/SelfBillingPaySuccess?item=${JSON.stringify(this.form)}`
				})
			}
		},
	}
</script>

<style scoped>
	.mask {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100vh;
	}

	.mask-content {
		background-color: white;
		padding: 15px 30px;
		border-radius: 16px;
	}

	.notice {
		text-align: center;
		background-color: rgb(248, 232, 231);
		color: rgb(249, 73, 29);
		line-height: 30px;
	}

	.dashed {
		border-bottom: 1px dashed gray;
		padding: 10px;
	}

	.wxzf {
		border: 1px solid rgb(241, 204, 197);
	}

	.ybzf {
		border: 1px solid rgb(241, 204, 197);
		border-top: none;
	}

	.img {
		width: 20px;
		height: 20px;
	}

	.notice-text {
		background-color: rgb(255, 250, 242);
		color: orange;
	}

	.btn-register {
		width: 60%;
		border-radius: 45rpx;
		margin: 15rpx;
		background-color: rgb(112, 222, 230);
	}
</style>